"""请款向导"""

from datetime import datetime

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


class RequestWizard(models.TransientModel):
    _name = 'create.request.tax.wizard'

    partner_id = fields.Many2one('res.partner', '客户')
    tax_ticket_type_id = fields.Many2one('nd.invoice.info', string="开票信息")
    payment_type_ids = fields.Many2many('account.journal', string="付款方式", required=True,
                                        domain=[('type', 'in', ['cash', 'bank'])])
    tax = fields.Boolean("是否含税")  # 用来记录该发票是否含税
    user_account_name = fields.Char('用户名', related="tax_ticket_type_id.name")
    user_bank_name = fields.Char('开户行', related="tax_ticket_type_id.opening_bank")
    user_bank_account = fields.Char('卡号', related="tax_ticket_type_id.customer_invoice_bank_account")

    @api.onchange('tax_ticket_type_id')
    def get_partner(self):
        if not self.tax_ticket_type_id:
            try:
                line = self.env.context.get('active_ids')[0]
                self.partner_id = self.env['purchase.payment'].search([('id', '=', line)]).partner_id.id
            except Exception as e:
                self.partner_id = None
        ids = self.env.context.get('active_ids', [])
        for line in self.env['purchase.payment'].browse(ids):
            if line.taxes_id:
                self.tax = True
                return

    @api.multi
    def confirm(self):
        # product_fee = product_tax = tax_total = 0
        self.ensure_one()
        invoice_name = None
        ids = self.env.context.get('active_ids', [])
        if not self.tax_ticket_type_id:
            raise UserError('请添加开票信息！')
        for line in self.env['purchase.payment'].browse(ids):
            if line.state == 'invoiced':
                raise UserError('勾选了处于已开票状态的明细表，明细表不能重复开票！')
            if invoice_name is not None and line.partner_id != invoice_name:
                raise UserError('同时只能为一个客户开票，请确保你选择的明细行属于同一客户！')
            else:
                invoice_name = line.partner_id
            # product_fee += line.sale_fee
            # product_tax += line.sale_tax
            # tax_total += line.sale_tax
        # TODO 是否需要检测有未结算的发票？
        partner_id = invoice_name.id
        # 根据所选的付款方式，生成对应的付款方式明细
        payment_detail_ids = self.create_payment_detail()
        account_payment_vals = {
            'partner_id': partner_id,
            'request_user': self.env.user.id,
            # 'state':'financial_approve',
            'request_date': datetime.now().date(),
            'user_account_name': self.user_account_name,
            'user_bank_name': self.user_bank_name,
            'user_bank_account': self.user_bank_account,
            # 'money_rebate_amount' :self._get_money_rebate_amount(),
            # 'payment_type':self.payment_type.id,
            'payment_type_ids': [(6, 0, payment_detail_ids)]
        }
        wiz = self.env['purchase.request.payment'].create(account_payment_vals)
        self.update_tax_line(line_ids=ids, tax_id=wiz.id)

        copy_list = self.tax_line_copy(tax_id=wiz.id, active_ids=ids)
        # amount = self.calc_amount(copy_list)
        # 将新建的请款单 与 请款明细copy 关联
        wiz.update({'account_payment_line': [(6, 0, copy_list)]})

        view = self.env.ref('nd_purchase_payment.purchase_request_payment_form_view')

        return {
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'purchase.request.payment',
            'views': [(view.id, 'form')],
            'view_id': view.id,
            'res_id': wiz.id,
            'context': self.env.context,
        }

    def calc_amount(self, copy_list):
        amount = 0
        for line in self.env['account.payment.line'].browse(copy_list):
            amount += line.this_amount
        return amount

    def update_tax_line(self, line_ids=(), tax_id=None):
        # 将新建的请款 与 请款明细（原单）关联
        for line in self.env['purchase.payment'].browse(list(line_ids)):
            if line:
                line.update({'purchase_request_id': [(4, tax_id, 0)]})

    def tax_line_copy(self, tax_id=None, active_ids=()):
        # 创建account.payment.line，就是请款单明细copy
        copy_list = []
        for num in active_ids:
            copy = self.env['account.payment.line'].create({
                'origin' :num,
                'purchase_request_payment': tax_id,
            })
            copy.update({'this_amount' :copy.total - copy.requested_amount})
            copy_list.append(copy.id)
        return copy_list

    def create_payment_detail(self):
        detail_ids = []
        detail = self.env['purchase.request.payment.detail']

        if not self.payment_type_ids:
            raise UserError('请添加付款方式！')

        for payment_type in self.payment_type_ids:
            detail_ids.append(detail.create({'payment_type' :payment_type.id}).id)
        return detail_ids

    # def _create_rebate_detail(self, ids):
    #     ticket = self.env['request.tax.ticket.line'].browse(ids[0])
    #     register_user = ticket.purchase_id.xdl_purchase_id.id
    #     for line in self.rebate_line_ids:
    #         table = self.env['purchase.return.line']
    #         rebate_fee_product = self.env['product.product'].search([('name' ,'=' ,'供应商返利'), ('can_be_expensed' ,'=' ,True)])
    #         if not rebate_fee_product:
    #             raise UserError('没有检索到返利费用产品，请创建一个名为“供应商返利”、可用于费用的产品')
    #
    #         if line.rebate_amount > 0:
    #             x = table.create({
    #                 'product_id' :rebate_fee_product[0].id,
    #                 'partner_id' :self.partner_id.id,
    #                 'price' :line.rebate_amount,
    #                 'time' :datetime.now().date(),
    #                 'purchase_rebate_id' :line.rebate_id.id,
    #                 'rebate_type' :'money_rebate',
    #                 'register_user': register_user,
    #             })